<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        effect="dark">
      </el-alert>
      <div style="margin: 15px 0">
        选择商品分类：
       <el-cascader
          v-model="cascaderValue"
          :options="cates"
          :props="cascaderProps"
          @change="cascaderChange">
       </el-cascader>
      </div>
      <div>
        <!-- tabs标签页 -->
       <el-tabs @tab-click="tabsclick" v-model="activeName">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="buttonIsDisabled" size="mini" type="primary" @click="addParamaDialogVisible=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="removeTag(scope.row, index)" closable v-for="(item, index) in scope.row.attr_vals" :key="index">
                  {{ item }}
                </el-tag>
                <el-input class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                style="width: 120px;"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+newTag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamsDialog(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="buttonIsDisabled" size="mini" type="primary" @click="addParamaDialogVisible=true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="removeTag(scope.row, index)" closable v-for="(item, index) in scope.row.attr_vals" :key="index">
                  {{ item }}
                </el-tag>
                <el-input class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                style="width: 120px;"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+newTag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParamsDialog(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
        </el-tab-pane>
      </el-tabs>
      </div>
    </el-card>

    <!-- 添加动态参数和静态属性对话框 -->
    <el-dialog
      :title="'添加' + (activeName === 'many' ? '动态参数' : '静态属性')"
      :visible.sync="addParamaDialogVisible"
      width="50%">
      <el-form ref="addParamsFormRef" :model="addParamsForm" label-width="80px" :rules="addParamsFormRules">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamaDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑动态参数和静态属性对话框 -->
    <el-dialog
      :title="'添加' + (activeName === 'many' ? '动态参数' : '静态属性')"
      :visible.sync="editParamaDialogVisible"
      width="50%">
      <el-form ref="editParamsFormRef" :model="editParamsForm" label-width="80px" :rules="editParamsFormRules">
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamaDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cates: [],
      cascaderValue: '',
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name', // 将哪个属性渲染到页面
        value: 'cat_id' // 将哪个属性保存下来
      },
      activeName: 'many',
      onlyTableData: [],
      manyTableData: [],
      addParamaDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },
      // 编辑修改对话框数据
      editParamaDialogVisible: false,
      editParamsForm: {
        attr_name: ''
      },
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    buttonIsDisabled () {
      return this.cascaderValue.length !== 3
    },
    cateId () {
      if (this.cascaderValue.length === 3) {
        return this.cascaderValue[2]
      }
      return null
    }
  },
  created () {
    this.getGoodsCate()
  },

  methods: {
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      this.cates = res.data
    },
    // 获取动态参数和静态属性
    async getParams () {
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      // res.data 可能是静态属性和动态参数
      // item.attr_vals:"12 34 56"
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      } else {
        this.manyTableData = res.data
      }
    },
    // 级联选择期发生变化
    async cascaderChange () {
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.onlyTableData = []
        this.manyTableData = []
      } else {
        this.getParams()
      }
    },
    // 点击tabs标签页
    tabsclick () {
      if (this.cateId) {
        this.getParams()
      }
    },
    // 点击确定添加参数和属性
    addParamsSubmit () {
      this.$refs.addParamsFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.addParamaDialogVisible = false
        this.getParams()
      })
    },
    // 点击修改
    showEditParamsDialog (row) {
      // console.log(row)
      // this.editParamsForm = row
      const { attr_name: attrName, attr_id: attrId } = row
      this.editParamsForm.attr_name = attrName
      this.editParamsForm.attr_id = attrId
      this.editParamaDialogVisible = true
    },
    // 点击确定编辑参数
    editParamsSubmit () {
      this.$refs.editParamsFormRef.validate(async flag => {
        if (!flag) return
        const attrId = this.editParamsForm.attr_id
        console.log(attrId)
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${attrId}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.editParamaDialogVisible = false
        this.getParams()
      })
    },
    // 点击删除
    removeParams (attrId) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${attrId}`)
        if (res.meta.status !== 200) this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParams()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 敲回车或者失去焦点事件
    handleInputConfirm (row) {
      console.log(row.inputValue)
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        row.inputValue = ''
        return true
      }
      // 实现添加功能
      row.attr_vals.push(row.inputValue)
      this.updateAttrVals(row)
    },
    showInput (row) {
      // 代码走到这一行，仅仅代表数据已经改变了，页面在异步同步中
      row.inputVisible = true
      // 数据驱动 代码
      // 代表当前组件页面已经更新完毕了
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 更新参数
    async updateAttrVals (row) {
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      row.inputVisible = false
      row.inputValue = ''
      this.$message.success('更新成功')
    },
    // 点击移除参数
    removeTag (row, index) {
      row.attr_vals.splice(index, 1)
      this.updateAttrVals(row)
    }
  }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 7px;
}
</style>
